<template>
	<view>
		<!-- 已经获取到用户数据，显示头像等数据 -->
		<view class="padding bg-white" v-if="hasLogin">
			<image class="cu-avatar round xl" :src='userInfo.avatar'></image>
			<view class="basis-sm login">
				<text class="text-bold text-lg">{{userInfo.nickname}}</text>
				<text class="text-gray">积分余额：{{userInfo.balance}}</text>
			</view>
			<view class="basis-sm detail" @click="gotoUrl('./userDetail')">
				<i class='iconfont'>&#xe665;</i>
			</view>
			<!-- 未登录时候显示登录框 -->
		</view>
		<view class="padding bg-white" v-if="!hasLogin">
			<image class="cu-avatar round xl" src='../../static/icon/tarBar_profile.png'></image>
			<view class="basis-sm">
				<button type="default" @tap="getUserInfo">点击登录</button>
			</view>
		</view>

		<!-- 功能菜单 -->
		<view class="cu-list menu margin-top">
			<view class="cu-item arrow">
				<button class="cu-btn content" @click="gotoUrl('./myGiftsOrders')">
					<image style="height: 65rpx; width: 65rpx;" src="../../static/icon/profile/gitftsLog.png"></image>
					<text class="text-grey">纪念品兑换订单</text>
				</button>
			</view>
			<view class="cu-item arrow">
				<button class="cu-btn content" @click="gotoUrl('./myActivityOrders')">
					<image style="height: 65rpx; width: 65rpx;" src="../../static/icon/profile/actLog.png"></image>
					<text class="text-grey">报名的活动</text>
				</button>
			</view>
			<view class="cu-item arrow">
				<button class="cu-btn content" @click="gotoUrl('./balanceChangeLog')">
					<image style="height: 65rpx; width: 65rpx;" src="../../static/icon/profile/balanceLog.png"></image>
					<text class="text-grey">积分记录</text>
				</button>
			</view>
			<view class="cu-item arrow">
				<button class="cu-btn content" @click="gotoUrl('./picOrders')">
					<image style="height: 65rpx; width: 65rpx;" src="../../static/icon/profile/picActLog.png"></image>
					<text class="text-grey">打卡记录</text>
				</button>
			</view>
			<view class="cu-item arrow">
				<button class="cu-btn content" @click="gotoUrl('./booksOrders')">
					<image style="height: 65rpx; width: 65rpx;" src="../../static/icon/profile/booksLog.png"></image>
					<text class="text-grey">图书借阅</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import utils from '@/common/utils.js';
	import shareMsg from '@/common/shareMessage.js';
	const db = uniCloud.database();
	// const uniID = require('uni-id');
	
	const app = getApp();
	export default {
		data() {
			return {
				menuArrow: true,
				menuBorder: false,
				menuCard: false,
				userInfo: {},
				wxUserInfo: {},
				provider: '',
				hasLogin: false,
				isAdmin: false,
				scores: null
			}
		},

		onShow() {
			this.hasLogin = app.globalData.hasLogin;
			this.userInfo = app.globalData.userInfo;
		},
		onShareAppMessage(){
			return shareMsg.shareMsg({
				title: 'AIIT百宝箱',
				path: '/pages/index/index',
				imageUrl: '/static/img/shareImg.png'
			})
		},

		methods: {
			/**
			 * 下拉刷新回调函数
			 */
			onPullDownRefresh() {
				app.onLaunch();
			},
			// 微信登陆
			getWeixinCode() {
				return new Promise((resolve, reject) => {
					// #ifdef APP-PLUS
					weixinAuthService.authorize(function(res) {
						resolve(res.code)
					}, function(err) {
						console.log(err)
						reject(new Error('微信登录失败'))
					});
					// #endif
					// #ifdef MP-WEIXIN
					uni.login({
						provider: 'weixin',
						success(res) {
							resolve(res.code)
						},
						fail(err) {
							reject(new Error('微信登录失败'))
						}
					})
					// #endif
				})
			},
			
			async loginByWeixin(e) {
				this.getWeixinCode().then((code) => {
					return uniCloud.callFunction({
						name: 'user-center',
						data: {
							action: 'loginByWeixin',
							params: {
								code,
							}
						}
					})
				}).then((res) => {
					uni.showToast({
						title: "登陆成功",
						complete: () => {
							app.globalData.userInfo = res.result.userInfo;
							this.userInfo = res.result.userInfo;
							app.globalData.hasLogin = true;
							this.hasLogin = true;
							uni.setStorageSync('sessionKey', res.result.sessionKey)
						}
					})
					if (res.result.code === 0) {
						db.collection('uni-id-users').doc(res.result.uid).update({
							nickname: this.wxUserInfo.nickName,
							gender: this.wxUserInfo.gender,
							avatar:this.wxUserInfo.avatarUrl
						})
						uni.setStorageSync('uni_id_token', res.result.token)
						uni.setStorageSync('uni_id_token_expired', res.result.tokenExpired)
					}
					if (res.result.type == 'login') {
						console.log("欢迎回来")
					} else if (res.result.type == "register") {
						uni.showModal({
							title: "请完善个人资料",
							success: (res) => {
								if (res.confirm) {
									uni.navigateTo({
										url: "../profile/userDetail"
									})
								}
							}
						})
					}
				}).catch((e) => {
					console.error(e)
					uni.showModal({
						showCancel: false,
						content: '微信登录失败，请稍后再试'
					})
				})
			},
			// 获取用户微信基础信息
			getUserInfo: function() {
				var that = this;
				uni.getUserProfile({
					desc: '微信登陆',
					complete: function(infoRes) {
						that.loginByWeixin()
						that.wxUserInfo = infoRes.userInfo;
						}
						})
				
						
			},
			
			gotoUrl: function(url) {
				uni.navigateTo({
					url: url,
					fail: (res) => {
						if (res.errMsg == "navigateTo:fail can not navigateTo a tabbar page") {
							uni.switchTab({
								url:url
							})
						}
					}
				})
			}
		},
	}
</script>

<style>
	.padding {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.cu-avatar.lg {
		width: 120upx;
		height: 120upx;
		font-size: 2em;
	}

	.text-center {
		padding: 20rpx;
		text-align: center;
	}

	.basis-sm {
		display: flex;
		padding: 0 0 0 30rpx;
		height: 100upx;
		flex-basis: 40%;
		align-items: center;
	}

	.basis-sm.login {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: flex-start;
		flex-basis: 40%;
	}

	.basis-sm.detail {
		padding: 0;
		height: 100upx;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		flex-basis: 40%;
	}
</style>
